/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Adapted for use with ABAP To Phone by John Patterson
 */
package com.jasper.android.atp;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.util.Log;

public class C2DMReceiver extends BroadcastReceiver {

	private static final String TAG = "C2DMReceiver";
	private static final String REGISTRATION = "com.google.android.c2dm.intent.REGISTRATION";
	private static final String RECEIVE = "com.google.android.c2dm.intent.RECEIVE";
	private static final String UPDATEFILTER = "com.jasper.android.atp.intent.UPDATE";
	private static final String EXTRA_UNREGISTERED = "unregistered";
	private static final String TITLESTR = "title";
	private static final String CONTENTSTR = "content";
	private static final String TYPESTR = "type";

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i(TAG, "onReceive");

		if (intent.getAction().equals(REGISTRATION)) {
			String removed = intent.getStringExtra(EXTRA_UNREGISTERED);
			if (removed != null) {
				onUnregister(context);
			} else {
				onRegistered(context, intent);
			}
		} else if (intent.getAction().equals(RECEIVE)) {
			onMessage(context, intent);
		}
	}

	public void onRegistered(Context context, Intent intent) {
		String reg = intent.getStringExtra(DeviceRegistrar.REGISTRATION_ID);
		DeviceRegistrar.registerWithServer(context, reg);
	}

	public void onUnregister(Context context) {
		DeviceRegistrar.unregisterWithServer(context);
	}

	protected void onMessage(Context context, Intent intent) {
		// the msg uses a simple convention of type, content and title
		// title - what is displayed in the notification
		// type - how to handle
		// content - could be a value or value pairs
		Intent launchIntent = null;
		Bundle extras = intent.getExtras();
		if (extras != null) {
			Log.i(TAG, "Message Received");

			// A couple of examples
			String title = (String) extras.getString(TITLESTR);
			String content = (String) extras.getString(CONTENTSTR);
			String type = (String) extras.getString(TYPESTR);

			if (type.equals("url")) {
				// set intent to open url
				launchIntent = new Intent(Intent.ACTION_VIEW,
						Uri.parse(content));
				launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				generateNotification(context, content, title, launchIntent);
			} else if (type.equals("tel")) {
				// set intent to open dialer, put number in clip boad
				launchIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ content));
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				generateNotification(context, content, title, launchIntent);
				ClipboardManager cm = (ClipboardManager) context
						.getSystemService(Context.CLIPBOARD_SERVICE);
				cm.setText(content);
			} else if (type.equals("sync")) {
				// rather than call applicable update service directly
				// broadcast update to anyone listening filter on string
				launchIntent = new Intent();
				launchIntent.setAction(UPDATEFILTER);
				launchIntent.putExtra(TITLESTR, title);
				launchIntent.putExtra(CONTENTSTR, content);
				context.sendBroadcast(launchIntent);
			} else if (type.equals("sapdata")){
				//send notification which opens the SAPData explorer
				PackageManager manager = context.getPackageManager();			 
				launchIntent =  manager.getLaunchIntentForPackage("org.sapmentors.android.gateway.sapdata");
				launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//				launchIntent.setData("incomingUri");
//				context.startActivity(launchIntent);
				generateNotification(context, content, title, launchIntent);
		} else {
				launchIntent = new Intent();
				generateNotification(context, content, title, launchIntent);
			}
		}
	}

	public void generateNotification(Context context, String msg, String title,
			Intent intent) {
		// setup notification with an icon, sound and message
		int icon = R.drawable.status_icon;
		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, title, when);
		notification.setLatestEventInfo(context, title, msg,
				PendingIntent.getActivity(context, 0, intent, 0));
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		// to allow multi notification store previous message
		SharedPreferences settings = Prefs.get(context);
		int notificatonID = settings.getInt("notificationID", 0); 

		NotificationManager nm = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		nm.notify(notificatonID, notification);
		playNotificationSound(context);

		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("notificationID", ++notificatonID % 32);
		editor.commit();

	}

	public void playNotificationSound(Context context) {
		Uri uri = RingtoneManager
				.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		if (uri != null) {
			Ringtone rt = RingtoneManager.getRingtone(context, uri);
			if (rt != null) {
				rt.setStreamType(AudioManager.STREAM_NOTIFICATION);
				rt.play();
			}
		}

	}
}
